package com.owen.java.demo.spl;

import java.sql.*;

public class RunSpl {

    /**
     * 基本使用 http://d.raqsoft.com.cn:6999/esproc/tutorial/jdbcjbsy.html
     * @throws ClassNotFoundException
     * @throws SQLException
     */
    public void runSPL() throws ClassNotFoundException, SQLException {
        Connection con = getConnection();
        PreparedStatement st;
        //直接执行SPL语句，返回结果集
        st = con.prepareCall("call test()");
        ResultSet rs = st.executeQuery();
        //简单处理结果集，将结果集中的字段名与数据输出
        extracted(rs);
        //关闭连接
        if (con != null) {
            con.close();
        }
    }

    /**
     * 配置服务 http://d.raqsoft.com.cn:6999/esproc/tutorial/fuwuqi.html#%E6%9C%8D%E5%8A%A1%E5%99%A8
     * 配置网关 http://d.raqsoft.com.cn:6999/esproc/tutorial/jdbcwangguan.html
     * @throws ClassNotFoundException
     * @throws SQLException
     */
    public void runSQL() throws ClassNotFoundException, SQLException {
        Connection con = getConnection();
        Statement st;
        //直接执行SPL语句，返回结果集
        st = con.createStatement();
        ResultSet rs = st.executeQuery("select * from demo_gdp_by_city");
        //简单处理结果集，将结果集中的字段名与数据输出
        extracted(rs);
        //关闭连接
        if (con != null) {
            con.close();
        }
    }

    private void extracted(ResultSet rs) throws SQLException {
        ResultSetMetaData rsmd = rs.getMetaData();
        int colCount = rsmd.getColumnCount();
        for (int c = 1; c <= colCount; c++) {
            String title = rsmd.getColumnName(c);
            if (c > 1) {
                System.out.print("\t");
            } else {
                System.out.print("\n");
            }
            System.out.print(title);
        }
        while (rs.next()) {
            for (int c = 1; c <= colCount; c++) {
                if (c > 1) {
                    System.out.print("\t");
                } else {
                    System.out.print("\n");
                }
                Object o = rs.getObject(c);
                System.out.print(o);
            }
        }
    }

    private Connection getConnection() throws ClassNotFoundException, SQLException {
        Connection con = null;
        PreparedStatement st;
        ResultSet set;
        //建立连接
        Class.forName("com.esproc.jdbc.InternalDriver");
        con = DriverManager.getConnection("jdbc:esproc:local://onlyServer=true");
        return con;
    }

}
